package com.hzqy.web.ac;

import java.io.*;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.hzqy.commons.utils.*;
import com.hzqy.service.hotel.WechatHotelService;
import com.hzqy.service.pms.PmsServiceBean;
import com.hzqy.web.vo.PmsUserVo;
import com.hzqy.web.vo.pms.PmsLoginAspectVo;
import com.hzqy.web.vo.wchat.LoginMessage.ReceiveMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.service.wchat.WechatWXService;

import static java.lang.Integer.numberOfLeadingZeros;
import static java.lang.Integer.parseInt;
import static java.lang.Math.round;

@Controller
@RequestMapping("/wchat")
public class WchatAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	WechatWXService wechatWXService;

	@Resource
	WechatHotelService wechatHotelService;
	@Resource
	private PmsServiceBean pmsServiceBean;
	/**
	 * 微信接入
	 *
	 * @param
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/connect")
	public void connectWeixin(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "signature", required = false) String signature,
			@RequestParam(value = "timestamp", required = false) String timestamp,
			@RequestParam(value = "nonce", required = false) String nonce,
			@RequestParam(value = "echostr", required = false) String echostr) throws IOException {
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号对接 验证Token, 参数: signature: " + signature + " timestamp: " + timestamp + " nonce: " + nonce + " echostr: " + echostr);

		request.setCharacterEncoding("UTF-8"); // 微信服务器POST消息时用的是UTF-8编码，在接收时也要用同样的编码，否则中文会乱码；
		response.setCharacterEncoding("UTF-8"); // 在响应消息（回复消息给用户）时，也将编码方式设置为UTF-8，原理同上；
		PrintWriter out = response.getWriter();
		Locale.setDefault(Locale.ENGLISH);
		try {
			if (request.getMethod().toLowerCase(Locale.ENGLISH).equals("get")) {
				String result = wechatWXService.connect(signature, timestamp, nonce, echostr);
				LOG.debug("(" + t1 + ")微信公众号对接  验证Token返回: " + result + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
				WChatUtil.printToWriter(response.getWriter(), result);
			} else {
				try {
					String respMessage = wechatWXService.weixinPost(request);
					if(respMessage != null)
						out.write(respMessage);
					else
						out.write("");
					LOG.debug("The request completed successfully");
					LOG.debug("to weixin server " + respMessage);
				} catch (Exception e) {
					LOG.error("Failed to convert the message from weixin!", e);
				}
			}
		} catch (Exception e) {
			LOG.error("Connect the weixin server is error.", e);
		} finally {
			out.close();
		}
	}

	/**
	 * 获取access_token
	 *
	 * 获取失败示例 : {"errcode":40013,"errmsg":"invalid appid"}
	 * 获取成功示例 : {\"access_token\":\"rKo_nFaLuzGOJPGn-pRzQ0oHDPpeWUmX15Cwvqo-cyxHpBMB-lRNqSamjZcTG4pin5_ZeXSr8wRpfMsxIaOEsukxCOiB7jb-dSEAjgEtyGBcySDqgCUobOdifW7AKW3tTIBdAFAHWP\",\"expires_in\":7200}
	 *
	 */
	@RequestMapping(value = "/access_token")
	@ResponseBody
	public Object access_token(){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号access_token获取接口");
		Map<String, String> resultMap = wechatWXService.access_token_I();
		LOG.debug("(" + t1 + ")微信公众号access_token获取接口返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 获取微信服务器IP列表
	 *
	 */
	@RequestMapping(value = "/wx_server_ips")
	@ResponseBody
	public Object wx_server_ips(){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号微信服务器IP获取接口");
		Map<String, String> resultMap = wechatWXService.wx_service_ips_I();
		LOG.debug("(" + t1 + ")微信公众号微信服务器IP获取获取接口返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 获取微信jsapi_ticket (js上的access_token)
	 */
	@RequestMapping(value = "/jsapi_ticket")
	@ResponseBody
	public Object jsapi_ticket(){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号微信服务器IP获取接口");
		Map<String, String> resultMap = wechatWXService.jsapi_ticket();
		LOG.debug("(" + t1 + ")微信公众号微信服务器IP获取获取接口返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 获取微信jsapi_config
	 */
	@RequestMapping(value = "/jsapi_config")
	@ResponseBody
	public Object jsapi_config(@RequestParam(value = "currentUrl", required = false) String currentUrl, HttpServletRequest request){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号生成jsapi配置");
		if(StringUtils.isEmpty(currentUrl)) {
			currentUrl = request.getRequestURL().toString();
		}
		Map<String, Object> resultMap = wechatWXService.jsapi_config(currentUrl);
		LOG.debug("(" + t1 + ")微信公众号生成jsapi配置返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 自定义微信个性化菜单
	 */
	@RequestMapping(value = "/create_menu")
	@ResponseBody
	public Object create_menu(){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号个性化菜单");
		Map<String, String> resultMap = wechatWXService.create_menu();
		LOG.debug("(" + t1 + ")微信公众号个性化菜单返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 微信授权回调 通过code获取用户信息(openid)
	 */
	@RequestMapping(value = "/openid_bycode")
	@ResponseBody
	public Object openid_bycode(
			@RequestParam(value = "code", required = true) String code,
			@RequestParam(value = "state", required = false) String state){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号获取用户信息 参数: code: " + code + " state: " + state);
		Map<String, String> resultMap = wechatWXService.openid_bycode(code, state);
		LOG.debug("(" + t1 + ")微信公众号获取用户信息 返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}


	/**
	 * 微信获取用户信息接口
	 * oZcvDw0_5L1iuPgUNesiNOZymmU4
	 */
	@RequestMapping(value = "/user_info_by_openid")
	@ResponseBody
	public Object user_info_by_openid(@RequestParam(value = "openid", required = true) String openid){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")微信公众号获取用户信息接口 参数: openid: " + openid);
		Map<String, String> resultMap = wechatWXService.user_info_by_openid(openid);
		LOG.debug("(" + t1 + ")微信公众号获取用户信息接口 返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 获取微信 临时素材
	 * @param media_id media_id
	 * @param destDir 存储图片目录
	 *  最终存储路径是 destDir + "/" + media_id + ".jpg"
	 *
	 *
	 *  media_id=OkIo4vSuLxLrurR_8HkUs4L8vfGOxjTQGYSH7FOSGoMv61fptFN5GxADumDm6flr&destDir=F:\zb
	 *
	 */
	@RequestMapping(value = "/get_media")
	@ResponseBody
	public Object get_media(
			@RequestParam(value = "media_id", required = true) String media_id,
			@RequestParam(value = "destDir", required = true) String destDir){
		long t1 = System.currentTimeMillis();
		LOG.debug("(" + t1 + ")获取微信 临时素材");
		Map<String, Object> resultMap = wechatWXService.get_media(media_id, destDir);
		LOG.debug("(" + t1 + ")获取微信 临时素材返回: " + resultMap + " 耗时:" + (System.currentTimeMillis() - t1) + "ms");
		return resultMap;
	}

	/**
	 * 拿到二维码ticket
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/get_ticket")
	@ResponseBody
	public Map<String, Object> get_ticket(@RequestParam(value = "expire_seconds", required = true) String expire_seconds,
										  @RequestParam(value = "action_name", required = true) String action_name,
										  @RequestParam(value = "scene_id", required = true) int scene_id) throws UnsupportedEncodingException {
		Map<String,Integer> intMap = new HashMap<String,Integer>();
		intMap.put("scene_id",scene_id);
		Map<String,Map<String,Integer>> mapMap = new HashMap<String,Map<String,Integer>>();
		mapMap.put("scene", intMap);

		JSONObject json = new JSONObject();
		json.put("expire_seconds", expire_seconds);
		json.put("action_name", action_name);
		json.put("action_info", mapMap);
		return wechatWXService.get_ticket(json,scene_id);
	}

	/**
	 * 拿到二维码信息id
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/get_ewm_id")
	@ResponseBody
	public String get_ewm_id(@RequestParam(value = "id", required = true) String id){
		LOG.debug("拿到二维码信息id:"+id);
		return id;
	}

	/**
	 * 对接微信测试账号,方便本地调试,必须把本地ip端口映射到外网,才能使用
	 * 对应微信公众号测试账号管理内的 接口配置信息 选项
	 */
	@RequestMapping("/testNumber")
	@ResponseBody
	public void testNumber(
			@RequestParam(value = "signature", required = true) String signature,
			@RequestParam(value = "timestamp", required = true) String timestamp,
			@RequestParam(value = "nonce", required = true) String nonce,
			@RequestParam(value = "echostr", required = true) String echostr,
			HttpServletResponse res) throws IOException {
		if(echostr==null)echostr="";
		PrintWriter out= res.getWriter();
		out.print(echostr);
		out.close();
	}

	/**
	 *公众号短信验证
	 * 登录页发送短信
	 */

	@PostMapping("/sendLoginMessage")
	@ResponseBody
	public Object sendMessage(String name,String phones,int smsType,String login_type) throws UnsupportedEncodingException {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
				"|(18[0-9])|(19[8,9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phones);
		if("2".equals(login_type)){

		}else{
			if(!m.matches()){
				LOG.debug("微信短信发送，手机号码有误，"+phones);
				resultMap.put("resCode",1001);
				return resultMap;
			}
		}
		PmsUserVo puv = new PmsUserVo();
		puv.setF_pu_phone(phones);
		puv.setF_pu_name(name);
		PmsUserVo resultVo = wechatHotelService.findUserOrgByPhone(puv);//数据库里有此账号才发
		if("2".equals(login_type)){
			phones=name;
		}
		if(resultVo==null){
			LOG.debug("微信短信发送，数据库无账号或者此账号无绑定组织，phones="+phones);
			resultMap.put("resCode",1004);
			return resultMap;
		}
		String sms_url = SystemConfigUtils.getSysConfig("SMS_url");

		//String userName="hzkdrjkf";
		//String userPassword="Ni5OLCkp";
		String userName=SystemConfigUtils.getSysConfig("SMS_userName");
		String userPassword=SystemConfigUtils.getSysConfig("SMS_userPassword");
		SecureRandom random = new SecureRandom();
		String tradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) +(int) (random.nextDouble() * (1000 -100) + 100);
		String content1 = ""+(int) (random.nextDouble() * (10))+(int) (random.nextDouble() * (10))+(int)+(random.nextDouble() * (10))+(int) (random.nextDouble() * (10));
		String content = SystemConfigUtils.getSysConfig("SMS_content")+content1;
		userPassword= MD5Util.MD5(userPassword);
		//url解码
		userName= URLDecoder.decode(userName,"utf-8");
		userPassword=URLDecoder.decode(userPassword,"utf-8");
		phones=URLDecoder.decode(phones,"utf-8");
		Map<String, Object> map = new HashMap<>();
		map.put("tradeNo",tradeNo);
		map.put("userName",userName);
		map.put("userPassword",userPassword);
		//map转化成json字符串
		String json = JSONObject.toJSONString(map);
		//密码由第三方（发财鱼）提供
		//String key="JsuIasUAwM1Wanfq";
		String key= SystemConfigUtils.getSysConfig("SMS_key");
		//AES对称加密算法进行加密，将加密结果转换为16进制字符串生成最终的数字签名
		String sign = AESUtil.encrypt(json,key);
		map.put("phones",phones);
		map.put("content",content);
		map.put("sign",sign);
		String param = JSONObject.toJSONString(map);
		//发送请求前先把数据存入数据库
		/*sendMessage vo = new sendMessage();
		vo.setTradeNo(tradeNo);
		wechatWXService.insert(vo);*/
		//String url ="http://apis.hzfacaiyu.com/sms/openCard";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		ReceiveMessage vo = new ReceiveMessage();
		vo.setPhones(phones);
		//String login_type = SystemConfigUtils.getSysConfig("login_type");
		vo.setLogin_type(login_type);
		vo.setSmsType(smsType);
		ReceiveMessage receiveMessage = wechatWXService.selectRSMS(vo);
		JSONObject jsonResult = new JSONObject();
		if(receiveMessage==null){
			String url=sms_url;
			String result = HttpUtil.postJsonS(url, param);
			if("".equals(result)){
				LOG.debug("请求失败");
			}else {
				//请求成功
			/*{
				"transNo" : "20150605101116323169",
				"resCode" : "P00000",
				"status" : 1,
                 “resMsg”:”提交成功”,
				"liuliuOrderId" : “20150605101116323165”,
			}*/
				jsonResult = JSONArray.parseObject(result);
				if("P00001".equals(jsonResult.get("resCode"))){
					LOG.debug("非法用户");
				}else if("P00002".equals(jsonResult.get("resCode"))){
					LOG.debug("参数错误");
				}else if("P00003".equals(jsonResult.get("resCode"))){
					LOG.debug("鉴权失败");
				}else if("P00004".equals(jsonResult.get("resCode"))){
					LOG.debug("系统异常");
				}else if("P00005".equals(jsonResult.get("resCode"))){
					LOG.debug("账户余额不足");
				}else if("P00010".equals(jsonResult.get("resCode"))){
					LOG.debug("手机号码过长");
				}else if("P00011".equals(jsonResult.get("resCode"))){
					LOG.debug("手机号码非法");
				}else if("P00009".equals(jsonResult.get("resCode"))){
					LOG.debug("其他未知错误");
				}else if("P00000".equals(jsonResult.get("resCode"))){
					LOG.debug("发送成功");
					if((int)jsonResult.get("status")==1){
						LOG.debug("处理中");
						LOG.debug(""+jsonResult);
						vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
						vo.setContent(content1);
						//vo.setPhones(phones);
						String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
						int times = parseInt(time, 10);

						vo.setStartTime(df.format(date));
						Date endTime = new Date(date.getTime() + times*60*1000);
						vo.setEndTime(df.format(endTime));
						vo.setLogin_type(login_type);
						vo.setSmsType(smsType);
						wechatWXService.insertRSMS(vo);
						//tokenList.add(token);
						//session.setAttribute("tokenList",tokenList);
					}else if((int)jsonResult.get("status")==0){
						LOG.debug("未处理");
					}else if((int)jsonResult.get("status")==5){
						LOG.debug("处理失败");
					}else if((int)jsonResult.get("status")==4){
						LOG.debug("处理成功");
						vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
						vo.setContent(content1);
						//vo.setPhones(phones);
						String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
						int times = parseInt(time, 10);

						vo.setStartTime(df.format(date));
						Date endTime = new Date(date.getTime() + times*60*1000);
						vo.setEndTime(df.format(endTime));
						vo.setLogin_type(login_type);
						vo.setSmsType(smsType);
						wechatWXService.insertRSMS(vo);
						//tokenList.add(token);
						//session.setAttribute("tokenList",tokenList);
					}
				}else{
					LOG.debug("其他未知错误");
				}
			}
		}else{
			jsonResult.put("state","短信有效期间");
		}
		return jsonResult;
	}


	/**
	 * 发送短信 现用于发随机密码
	 */

	@PostMapping("/sendPwdMessage")
	@ResponseBody
	public Object sendMessageContent(HttpSession session, String name,int smsType) throws UnsupportedEncodingException {
		Map<String,Object> resultMap = new HashMap<String,Object>();

		String phones = SystemConfigUtils.getSysConfig("admin_phones");
		String[] phoneArray = phones.toString().split(",");
		String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
				"|(18[0-9])|(19[8,9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		phones="";

		for (int i = 0; i < phoneArray.length; i++) {
			Matcher m = p.matcher(phoneArray[i]);
			if(!m.matches()){
				phoneArray[i]="";
			}
			else{
				phones+=phoneArray[i]+",";
			}
		}
		phones = phones.substring(0, phones.length() - 1);
		PmsUserVo puv = new PmsUserVo();
		puv.setF_pu_name(name);
		PmsUserVo resultVo = wechatHotelService.findUserOrgByName(puv);//数据库里有此账号才发

		if(resultVo==null){
			LOG.debug("数据库无账号或者此账号无绑定组织，phones="+phones);
			resultMap.put("result","请输入正确的账号");
			return resultMap;
		}
		String sms_url = SystemConfigUtils.getSysConfig("SMS_url");
		//String userName="hzkdrjkf";
		//String userPassword="Ni5OLCkp";
		String userName=SystemConfigUtils.getSysConfig("SMS_userName");
		String userPassword=SystemConfigUtils.getSysConfig("SMS_userPassword");
		SecureRandom random = new SecureRandom();
		String tradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) +(int) (random.nextDouble() * (1000 -100) + 100);

		String[][] c1 = {
				{"!", "@", "#", "$", "%", "^", "&"},
				{"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "{", "}", "|"},
				{"A", "S", "D", "F", "G", "H", "J", "K", "L", ":"},
				{"Z", "X", "C", "V", "B", "N", "M", "<", ">", "?"}
		};
		String[][] c2 = {
				{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", },
				{"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"},
				{"a", "s", "d", "f", "g", "h", "j", "k", "l"},
				{"z", "x", "c", "v", "b", "n", "m"}
		};

		String pwd =(int)(random.nextDouble()*10)+String.valueOf((char)(int)(random.nextDouble()*26+97))+c1[0][(int)(random.nextDouble()*6)];
		for (int i = 0; i < 5; i++) {
			if(round(random.nextDouble())==1){
				int row=(int)(random.nextDouble()*(4));
				pwd+=c1[row][(int)(random.nextDouble()*(c1[row].length-1))];
			}else{
				int row=(int)(random.nextDouble()*(4));
				pwd+=c2[row][(int)(random.nextDouble()*(c2[row].length-1))];
			}
		}
		String content1 = SystemConfigUtils.getSysConfig("SMS_pwd_content");
		String[] contents = content1.split(",");
		String content = contents[0]+name+contents[1]+pwd;

		userPassword= MD5Util.MD5(userPassword);
		//url解码
		userName= URLDecoder.decode(userName,"utf-8");
		userPassword=URLDecoder.decode(userPassword,"utf-8");
		phones = URLDecoder.decode(phones.toString(), "utf-8");
		Map<String, Object> map = new HashMap<>();
		map.put("tradeNo",tradeNo);
		map.put("userName",userName);
		map.put("userPassword",userPassword);
		//map转化成json字符串
		String json = JSONObject.toJSONString(map);
		//密码由第三方（发财鱼）提供
		//String key="JsuIasUAwM1Wanfq";
		String key= SystemConfigUtils.getSysConfig("SMS_key");
		//AES对称加密算法进行加密，将加密结果转换为16进制字符串生成最终的数字签名
		String sign = AESUtil.encrypt(json,key);
		map.put("phones", phones.toString());
		map.put("content",content);
		map.put("sign",sign);
		String param = JSONObject.toJSONString(map);
		//发送请求前先把数据存入数据库
		/*sendMessage vo = new sendMessage();
		vo.setTradeNo(tradeNo);
		wechatWXService.insert(vo);*/
		//String url ="http://apis.hzfacaiyu.com/sms/openCard";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		ReceiveMessage vo = new ReceiveMessage();
		vo.setPhones(phones);
		//String login_type = SystemConfigUtils.getSysConfig("login_type");
		String login_type="1";
		vo.setLogin_type(login_type);
		vo.setSmsType(smsType);
		JSONObject jsonResult = new JSONObject();
		String url=sms_url;
		String result = HttpUtil.postJsonS(url, param);
		if("".equals(result)){
			LOG.debug("请求失败");
		}else {
			//请求成功
			/*{
				"transNo" : "20150605101116323169",
				"resCode" : "P00000",
				"status" : 1,
                 “resMsg”:”提交成功”,
				"liuliuOrderId" : “20150605101116323165”,
			}*/
			jsonResult = JSONArray.parseObject(result);
			if("P00001".equals(jsonResult.get("resCode"))){
				LOG.debug("非法用户");
			}else if("P00002".equals(jsonResult.get("resCode"))){
				LOG.debug("参数错误");
			}else if("P00003".equals(jsonResult.get("resCode"))){
				LOG.debug("鉴权失败");
			}else if("P00004".equals(jsonResult.get("resCode"))){
				LOG.debug("系统异常");
			}else if("P00005".equals(jsonResult.get("resCode"))){
				LOG.debug("账户余额不足");
			}else if("P00010".equals(jsonResult.get("resCode"))){
				LOG.debug("手机号码过长");
			}else if("P00011".equals(jsonResult.get("resCode"))){
				LOG.debug("手机号码非法");
			}else if("P00009".equals(jsonResult.get("resCode"))){
				LOG.debug("其他未知错误");
			}else if("P00000".equals(jsonResult.get("resCode"))){
				LOG.debug("发送成功");
				if((int)jsonResult.get("status")==1){
					LOG.debug("处理中");
					LOG.debug(""+jsonResult);
					vo.setContent(pwd);
					//vo.setPhones(phones);
					String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
					int times = parseInt(time, 10);
					vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
					vo.setStartTime(df.format(date));
					Date endTime = new Date(date.getTime() + times*60*1000);
					vo.setEndTime(df.format(endTime));
					wechatWXService.insertRSMS(vo);

				}else if((int)jsonResult.get("status")==0){
					LOG.debug("未处理");
				}else if((int)jsonResult.get("status")==5){
					LOG.debug("处理失败");
				}else if((int)jsonResult.get("status")==4){
					LOG.debug("处理成功");
					vo.setContent(pwd);
					//vo.setPhones(phones);
					String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
					int times = parseInt(time, 10);

					vo.setStartTime(df.format(date));
					Date endTime = new Date(date.getTime() + times*60*1000);
					vo.setEndTime(df.format(endTime));
					vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
					wechatWXService.insertRSMS(vo);
				}
			}else{
				LOG.debug("其他未知错误");
			}
		}
		return jsonResult;
	}



	/**
	 *小程序增加短信验证
	 * 发送短信
	 */

	@PostMapping("/sendLoginMessageXCX")
	@ResponseBody
	public Object sendMessageXCX(HttpSession session, String phones) throws UnsupportedEncodingException {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
				"|(18[0-9])|(19[8,9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(phones);
		if(!m.matches()){
			LOG.debug("小程序短信发送，手机号码有误，"+phones);
			resultMap.put("resCode",1001);
			return resultMap;
		}

		PmsUserVo puv = new PmsUserVo();
		puv.setF_pu_name(phones);
		PmsUserVo resultVo = wechatHotelService.findUserOrgByPhone(puv);//数据库里有此账号才发

		if(resultVo==null){
			LOG.debug("微信短信发送，数据库无账号或者此账号无绑定组织，phones="+phones);
			resultMap.put("resCode",1004);
			return resultMap;
		}

		String sms_url = SystemConfigUtils.getSysConfig("SMS_url");

		//String userName="hzkdrjkf";
		//String userPassword="Ni5OLCkp";
		String userName=SystemConfigUtils.getSysConfig("SMS_userName");
		String userPassword=SystemConfigUtils.getSysConfig("SMS_userPassword");
		SecureRandom random = new SecureRandom();
		String tradeNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) +(random.nextInt()* (1000 -100) + 100);

		String content1 = ""+(random.nextInt() * (10))+(random.nextInt() * (10))+random.nextInt() * (10)+random.nextInt()* (10);
		String content = SystemConfigUtils.getSysConfig("SMS_content")+content1;
		userPassword= MD5Util.MD5(userPassword);
		//url解码
		userName= URLDecoder.decode(userName,"utf-8");
		userPassword=URLDecoder.decode(userPassword,"utf-8");
		phones=URLDecoder.decode(phones,"utf-8");
		Map<String, Object> map = new HashMap<>();
		map.put("tradeNo",tradeNo);
		map.put("userName",userName);
		map.put("userPassword",userPassword);
		//map转化成json字符串
		String json = JSONObject.toJSONString(map);
		//密码由第三方（发财鱼）提供
		//String key="JsuIasUAwM1Wanfq";
		String key= SystemConfigUtils.getSysConfig("SMS_key");
		//AES对称加密算法进行加密，将加密结果转换为16进制字符串生成最终的数字签名
		String sign = AESUtil.encrypt(json,key);
		map.put("phones",phones);
		map.put("content",content);
		map.put("sign",sign);
		String param = JSONObject.toJSONString(map);
		//发送请求前先把数据存入数据库
		/*sendMessage vo = new sendMessage();
		vo.setTradeNo(tradeNo);
		wechatWXService.insert(vo);*/
		//String url ="http://apis.hzfacaiyu.com/sms/openCard";
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		ReceiveMessage vo = new ReceiveMessage();
		vo.setPhones(phones);

		ReceiveMessage receiveMessage = wechatWXService.selectRSMS(vo);
		JSONObject jsonResult = new JSONObject();
		if(receiveMessage==null){
			String url=sms_url;
			String result = HttpUtil.postJsonS(url, param);
			if("".equals(result)){
				LOG.debug("请求失败");
			}else {
				//请求成功
			/*{
				"transNo" : "20150605101116323169",
				"resCode" : "P00000",
				"status" : 1,
                 “resMsg”:”提交成功”,
				"liuliuOrderId" : “20150605101116323165”,
			}*/
				jsonResult = JSONArray.parseObject(result);
				if("P00001".equals(jsonResult.get("resCode"))){
					LOG.debug("非法用户");
				}else if("P00002".equals(jsonResult.get("resCode"))){
					LOG.debug("参数错误");
				}else if("P00003".equals(jsonResult.get("resCode"))){
					LOG.debug("鉴权失败");
				}else if("P00004".equals(jsonResult.get("resCode"))){
					LOG.debug("系统异常");
				}else if("P00005".equals(jsonResult.get("resCode"))){
					LOG.debug("账户余额不足");
				}else if("P00010".equals(jsonResult.get("resCode"))){
					LOG.debug("手机号码过长");
				}else if("P00011".equals(jsonResult.get("resCode"))){
					LOG.debug("手机号码非法");
				}else if("P00009".equals(jsonResult.get("resCode"))){
					LOG.debug("其他未知错误");
				}else if("P00000".equals(jsonResult.get("resCode"))){
					LOG.debug("发送成功");
					if((int)jsonResult.get("status")==1){
						LOG.debug("处理中");
						LOG.debug(""+jsonResult);
						vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
						vo.setContent(content1);
						//vo.setPhones(phones);
						String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
						int times = parseInt(time, 10);

						vo.setStartTime(df.format(date));
						Date endTime = new Date(date.getTime() + times*60*1000);
						vo.setEndTime(df.format(endTime));
						wechatWXService.insertRSMS(vo);
					}else if((int)jsonResult.get("status")==0){
						LOG.debug("未处理");
					}else if((int)jsonResult.get("status")==5){
						LOG.debug("处理失败");
					}else if((int)jsonResult.get("status")==4){
						LOG.debug("处理成功");
						vo.setLiuliuOrderId((String) jsonResult.get("liuliuOrderId"));
						vo.setContent(content1);
						//vo.setPhones(phones);
						String time = SystemConfigUtils.getSysConfig("SMS_verification_time");
						int times = parseInt(time, 10);

						vo.setStartTime(df.format(date));
						Date endTime = new Date(date.getTime() + times*60*1000);
						vo.setEndTime(df.format(endTime));
						wechatWXService.insertRSMS(vo);
					}
				}else{
					LOG.debug("其他未知错误");
				}
			}
		}else{
			jsonResult.put("state","短信有效期间");
		}
		return jsonResult;
	}

	@PostMapping("/receiveLoginMessage")
	@ResponseBody
	public JSONObject receiveOrder(@RequestBody String message) throws UnsupportedEncodingException {
		message = URLDecoder.decode(message, "utf-8");
		//写入数据库
		JSONObject result = new JSONObject();
		//返回值
		JSONObject json = JSONObject.parseObject(message);

		if(json.get("tradeNo")==null){
			result.put("tradeNo","000000");
			result.put("resCode","P00002");
		}else{
			result.put("tradeNo",json.get("tradeNo"));
			if(json.get("liuliuOrderId")==null || json.get("type")==null){
				result.put("resCode","P00002");
			}else{
				result.put("resCode","P00000");
				ReceiveMessage vo = new ReceiveMessage();
				String[] liuliuOrderIds= ((String) json.get("liuliuOrderId")).split(";");
				for (String OrderId :liuliuOrderIds) {
					String[] id = OrderId.split(",");
					//S1621388741537612,18768306356,DELIVRD
					//订单号，号码，状态
					//接收成功
					if("DELIVRD".equals(id[2])){
						vo.setLiuliuOrderId(id[0]);
						vo.setMgs((String) json.get("mgs"));
						wechatWXService.updateRSMS(vo);
					}else{
						LOG.debug("回调1失败");
					}
				}

			}
		}
		return result;
	}


	/**
	 * 根据订单id查询内容
	 */
	@GetMapping("/reSMSByOrderId")
	@ResponseBody
	public ReceiveMessage select_reSMS(ReceiveMessage vo){
		return wechatWXService.selectRSMS(vo);
	}
	public static void main(String[] args) {
	/*	JSONObject json = new JSONObject();vo
		json.put("tradeNo","20150605101116323169 ");
		HashMap<String, Object> map = new HashMap<>();
		map.put("tradeNo","20150605101116323169 ");
		map.put("liuliuOrderId","20150605101116309878, 15257157671,DELIVRD");
		map.put("type",3);
		map.put("mgs","主动推送 ");
		System.out.println(json.get("mgs"));*/
	}


	@RequestMapping("/MessageCount")
	@ResponseBody
	public int selectMessage(ReceiveMessage sms){
		int count = wechatWXService.selectRSMSCount(sms);
		return count;
	}

	@RequestMapping("/smsInfo")
	@ResponseBody
	public Object selectMessageInfo(ReceiveMessage sms){
		HashMap<String, Object> map = new HashMap<>();
		//String login_type = SystemConfigUtils.getSysConfig("login_type");
		//sms.setLogin_type(login_type);
		ReceiveMessage receiveMessage = wechatWXService.selectRSMS(sms);
		if(receiveMessage!=null){
			map.put("orderId",receiveMessage.getLiuliuOrderId());
		}else{
			map.put("orderId","");
		}
		return map;
	}

}